package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.Allocation;
import Models.InsertedAllocations;

public class InsertedAllocationsPresenter extends AbstractPresenter<InsertedAllocations> {
	final String SINGLEITEM = "insertedAllocations";
	final String MULTIITEM = "insertedAllocationss";
	
	public ArrayList<InsertedAllocations> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public InsertedAllocations tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public InsertedAllocations createItemFromJSONObject(JSONObject jsonObject){
		InsertedAllocations item = new InsertedAllocations();
		try{
			//Set LabType Collection
			ArrayList<Allocation> allocations = new ArrayList<Allocation>();
			if(!jsonObject.isNull("allocations")){
				Object itm = jsonObject.get("allocations");
				AllocationPresenter presenter = new AllocationPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						allocations.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					allocations.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setAllocations(allocations);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(InsertedAllocations item){
		try{
			JSONObject json = new JSONObject();
			//Create Beers Collection
			if(item.getAllocations()!=null){
				AllocationPresenter presenter = new AllocationPresenter();
				if(item.getAllocations().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getAllocations().size(); i++){
						jsonArray.put(presenter.createJSON(item.getAllocations().get(i)));
					}
					json.put("allocations", jsonArray);
				}
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public InsertedAllocations getEmptyEntity(){
		InsertedAllocations entity = new InsertedAllocations();
		return entity;
	}
}
